//
//  EventAddPreviewController.m
//  whopaidforit
//
//  Created by Hoang Vu on 2/3/13.
//  Copyright (c) 2013 Hoang Vu. All rights reserved.
//

#import "EventAddPreviewController.h"
#import "Base64.h"

@interface EventAddPreviewController ()

@end

@implementation EventAddPreviewController

@synthesize viewAdd, txtTitle, btCurrency, scrollView;

@synthesize listData, listCurrency, currencyPicker, currencyId;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.listCurrency = [[NSMutableArray alloc] init];
    [self changeStyle];
    [self createNaviStyle];
    [self showGripUser];
    [self createPopup];
    [self hideDatePicker];
    [self loadData];
}
-(void) loadData
{
    Currency *currency = [Currency instance];
    self.listCurrency = [currency getList];
    Event *event =[Event instance];
    self.txtTitle.text = event._name;
    self.currencyId = event.currencyId;
    [self.btCurrency setTitle:event.currency forState:UIControlStateNormal];
}
-(void) changeStyle
{   
    [StyleControl background:self.view];
    [StyleControl setViewStyle:viewAdd];
    [StyleControl drawLine:self.viewAdd PositionX:0 PositionY:45 Width:306];
    [StyleControl drawLine:self.viewAdd PositionX:0 PositionY:90 Width:306];
}

-(void)createNaviStyle
{
    UIButton *left =[UIButton buttonWithType:UIButtonTypeRoundedRect];
    UIButton *right =[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [left addTarget:self action:@selector(eventList:) forControlEvents:UIControlEventTouchUpInside];
    [right addTarget:self action:@selector(saveEvent:) forControlEvents:UIControlEventTouchUpInside];
    [left setImage:[UIImage imageNamed:@"buttonlist"] forState:UIControlStateNormal];
    left.frame = CGRectMake(8, 8, 37, 35);
    right.frame = CGRectMake(250, 8, 60, 35);
    [right setTitle:@"Gereed" forState:UIControlStateNormal];
    [StyleControl  naviStyle:self.view andTitle:[NSString stringWithFormat:NSLocalizedString(@"event.add.title", @"")] andColor:0 andleftButton:left andRightButton:right borderLeft:1 borderRight:1];
}
-(void) createPopup{
    UIView *pickerView = [[UIView alloc] initWithFrame:CGRectMake(50, 140, 200, 150)];
    UIToolbar *datePickerTimerToolbar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 200, 40)] autorelease];
    datePickerTimerToolbar.barStyle=UIBarStyleBlackTranslucent;
    
    
    NSArray *barPickerTimerItems = [NSArray arrayWithObjects:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease], [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(hideDatePicker)] autorelease], nil];
    
    [datePickerTimerToolbar setItems:barPickerTimerItems animated:YES];
    [pickerView addSubview:self.currencyPicker];
    [pickerView addSubview:datePickerTimerToolbar];
    [self.view addSubview:pickerView];
    [pickerView setHidden:NO];
    currencyPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 200, 110)];
	
	currencyPicker.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
	//CGSize pickerSize = [myPickerView sizeThatFits:CGSizeZero];
	currencyPicker.frame = CGRectMake(0, 40, 200, 162);
    
	currencyPicker.showsSelectionIndicator = YES;	// note this is default to NO
	
	// this view controller is the data source and delegate
	currencyPicker.delegate = self;
	currencyPicker.dataSource = self;
	
	// add this picker to our view controller, initially hidden
    currencyPicker.hidden = NO;
	[pickerView addSubview:currencyPicker];
}

-(void)hideDatePicker
{
    [self.currencyPicker setHidden:YES];
    [self.currencyPicker.superview setHidden:YES];
}
-(void)showDatePicker
{
    [self.currencyPicker setHidden:NO];
    [self.currencyPicker.superview setHidden:NO];
}
-(void)showGripUser
{
    //[scrollView setBackgroundColor:[UIColor blueColor]];
    //scroll view
    for(UIView *subview in [self.scrollView subviews]) {
        [subview removeFromSuperview];
        //NSLog(@"Subviews Count=%d",myScrollView.subviews.count);
    }
    //number items per row
    int a=4;
    //number items per column
    int b=2;
    if([listData count] < 7) b = 2;
    //total items + 1 for add item in last
    int c=[self.listData count] + 1;
    //width of scrollView
    int d=scrollView.frame.size.width;
    //height of scrollView
    int d2=scrollView.frame.size.height;
    //width of an item
    int e=d/a;
    //height of an item
    int f=d2/b-15;
    int i=0;
    int numPages = ceil(1.0f*c/(a*b));
    for (int p=0; p<numPages; p++) {
        for (int m=0; m<b; m++) {
            for (int n=0; n<a && i<c; n++) {
                UIView *itemView = [[UIView alloc] initWithFrame:CGRectMake(((p*d)+(n*e)), (m*f), e, f)];
                if(i == c-1){
                    UIButton *addMemberButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    addMemberButton.frame = CGRectMake(0, -18, e, f);
                    [addMemberButton setImage:[UIImage imageNamed:@"addmember"] forState:UIControlStateNormal];
                    [addMemberButton addTarget:self action:@selector(showAddMember) forControlEvents:UIControlEventTouchUpInside];
                    [addMemberButton setTitle:@"Lid toevoegen" forState:UIControlStateNormal];
                    [itemView addSubview:addMemberButton];
                }else{
                    ParticipateClass *par = [self.listData objectAtIndex:i];
                    UIImageView *im = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
                    im.image = [Helper getImageMember:par];
                    /*if([par.image isEqualToString:@""] && par.idString){
                        NSString *urlString = [NSString stringWithFormat:@"http://graph.facebook.com/%@/picture",par.idString];
                        NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: urlString]];
                        UIImage *image = [[UIImage alloc] initWithData:imageData];
                        im.image = image;
                    }else{
                        [Base64 initialize];
                        NSData* data = [Base64 decode:par.image ];
                        im.image = [UIImage imageWithData:data];
                    }*/
                    
                    [StyleControl setBorderStyle:im];
                    [itemView addSubview:im];
                    [im release];
                    
                    UIImageView *icon = [[UIImageView alloc] init];
                    icon.frame = CGRectMake(10, 45, 15, 15);
                    if(par.approved == 1)
                        icon.image = [UIImage imageNamed:@"approved"];
                    else{
                        icon.frame = CGRectMake(10, 35, 25, 25);
                        icon.image = [UIImage imageNamed:@"sendBlue"];
                    }
                    [itemView addSubview:icon];
                    [icon release];
                    
                    UILabel *lblName = [[UILabel alloc] init];
                    lblName.text = par.name;
                    lblName.frame = CGRectMake(10, 60, 60, 20);
                    lblName.font = [UIFont systemFontOfSize:12];
                    [itemView addSubview:lblName];
                    [lblName release];
                }
                [scrollView addSubview:itemView];
                [itemView release];
                i++;
            }
        }
    }
    scrollView.contentSize = CGSizeMake(d*(numPages), d2);
    scrollView.pagingEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
}

-(void)showAddMember
{
    EventAddMemberController *detail = [[EventAddMemberController alloc] init];
    detail.tempArray=self.tempArray;
    [self presentViewController:detail animated:YES completion:NULL];
    [detail release];
}
-(IBAction)eventList:(id)sender
{
    EventListController *detail = [[EventListController alloc] init];
    [self presentViewController:detail animated:YES completion:NULL];
    [detail release];
}
-(IBAction)addCurrency:(id)sender
{
    [self showDatePicker];
}
-(IBAction)addPaid:(id)sender
{
    
}

-(IBAction)addMember:(id)sender
{
    EventAddMemberController *detail = [[EventAddMemberController alloc] init];
    [self presentViewController:detail animated:YES completion:NULL];
    [detail release];
}

-(IBAction)saveEvent:(id)sender
{
    //self.listData
    Event *event = [Event instance];
    User *user = [User instance];
    event._id = [event addEventWS:user._id eventName:self.txtTitle.text eventDescription:@"" Currency:self.currencyId];
    // save all member in that event
    Participate *par = [Participate instance];
    [par addForEvent:event._id ArrayMember:listData];
    BookingListController *detail = [[BookingListController alloc] init];
    detail.listNewUser = listData;
    [self presentViewController:detail animated:YES completion:NULL];
    [detail release];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // Any additional checks to ensure you have the correct textField here.
    [textField resignFirstResponder];
    return YES;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark UIPickerViewDataSource

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	CurrencyClass *cur;
    cur = [self.listCurrency objectAtIndex:row];
    NSString *returnStr = cur.name;
	return returnStr;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [self.listCurrency count];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}
-(void) pickerView:(CPPickerView *)pickerView didSelectItem:(NSInteger)row
{
    
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    CurrencyClass *cur;
    cur = [self.listCurrency objectAtIndex:row];
    [btCurrency setTitle:cur.name forState:UIControlStateNormal];
}
-(NSString *)pickerView:(CPPickerView *)pickerView titleForItem:(NSInteger)item
{
    return @"item";
}
-(NSInteger) numberOfItemsInPickerView:(CPPickerView *)pickerView
{
    return 4;
}
@end
